<template>
    <div>
        <el-form label-width="110px" size="small">
            <el-row class="form-row">
                <el-col :span="12">
                    <el-form-item label="产品代码:" v-if="isBatchStock">
                        <RiskEntryInput @set-entry-data="getEntryslist" :returnDatas="instruction.fundCode" />
                    </el-form-item>
                    <el-form-item label="组合编码:" v-if="isBatchStock">
                        <el-select v-model="instruction.fundAccountCode" size="mini">
                            <el-option
                                v-for="i in computedFundAccountCodeSelectData"
                                :key="i.fundAccountCode"
                                :label="i.fundAccountCode + '' + i.fundAccountName"
                                :value="i.fundAccountCode"
                                @change="handleFundAccountCodeChange"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证券代码:" v-if="isBatchFund">
                        <el-select
                            v-model="instruction.stockCode"
                            @change="handleStockCodeChange"
                            filterable
                            :filter-method="searchStockCodeList"
                            :loading="selectLoading"
                            size="mini"
                            clearable
                            @clear="handleClearStockCode"
                        >
                            <el-option
                                v-for="i in stockCodeSelectData"
                                :key="i.stockCode"
                                :label="i.stockCode + ' ' + i.stockNameSt"
                                :value="i.stockCode"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="业务类型:">
                        <el-select disabled size="mini" v-model="instruction.businessType">
                            <el-option label="银行间业务" value="2"> </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="委托方向:">
                        <el-select
                            v-model="instruction.orderDirection"
                            size="mini"
                            :class="instruction.orderDirection === '3' ? 'red-color' : instruction.orderDirection === '4' ? 'green-color' : ''"
                        >
                            <el-option value="3" label="债券买入" style="color: red">债券买入 </el-option>
                            <el-option value="4" label="债券卖出" style="color: #1c8d1c">债券卖出 </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="清算速度:">
                        <el-select size="mini" v-model="instruction.clearSpeed" @change="handleClearSpeedChange" :class="['font-color-' + textColor]">
                            <el-option v-for="i in clearSpeedSelectData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="净价价格:">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="instruction.orderPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :field="'orderPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        />
                    </el-form-item>
                    <el-form-item label="全价价格:">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="instruction.fullPrice"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :field="'fullPrice'"
                            @getInputNumber="getInputNumber(arguments)"
                        />
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="净价金额:">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="instruction.orderBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :field="'orderBalance'"
                            :disabled="true"
                            @getInputNumber="getInputNumber(arguments)"
                        />
                    </el-form-item>
                    <el-form-item label="券面总额:">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="stockFaceBalance"
                            inputAfter="万元"
                            :colorStyle="textColor"
                            :precision="4"
                            :field="'stockFaceBalance'"
                            @getInputNumber="getInputNumber(arguments)"
                        >
                        </RiskInputNumber>
                    </el-form-item>
                    <el-form-item label="结算日期:"
                        ><el-date-picker
                            v-model="instruction.firstSettleDate"
                            type="date"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                            style="width: 100%"
                        ></el-date-picker
                    ></el-form-item>
                    <el-form-item label="总应计利息:">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="instruction.totalInterest"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :field="'totalInterest'"
                            @getInputNumber="getInputNumber(arguments)"
                            :disabled="true"
                        />
                    </el-form-item>
                    <el-form-item label="结算金额:">
                        <RiskInputNumber
                            :maxlength="15"
                            :input="instruction.settlementBalance"
                            :inputAfter="'元'"
                            :colorStyle="textColor"
                            :precision="2"
                            :field="'settlementBalance'"
                            :disabled="true"
                        />
                    </el-form-item>
                    <el-form-item label="交易对手:">
                        <el-select
                            id="multiAndSearch"
                            v-model="instruction.opponentCode"
                            filterable
                            clearable
                            remote
                            :remote-method="getOpponentCode"
                            :loading="selectLoading"
                            size="mini"
                            @visible-change="changeSelect"
                        >
                            <el-option
                                v-for="i in opponentCodeSelectData"
                                :key="i.dictKey"
                                :label="i.dictKey + ' ' + i.dictKeyName"
                                :value="i.dictKey"
                            >
                            </el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import RiskInputNumber from '@/pages/risk-measure/components/risk-input-number.vue';
import { SelectOptionItemData } from '@/pages/risk-time/types/SelectOptionItemData';
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import { getBusinessType } from '@/pages/risk-time/api';
import { Dictionary } from '@/pages/risk-time/types/Dictionary';
import moment from 'moment';
import { handleTextColor } from '@/utils/tools';

@Component({
    name: 'BankBondForm',
    components: {
        RiskInputNumber,
        RiskEntryInput,
    },
})

// 银行间债券
export default class BankBondForm extends Vue {
    @Prop()
    detail: any;
    @Prop()
    selectStockInfo: any;
    @Prop()
    notMesh: boolean;
    @Prop()
    renderCount: number;
    @Prop()
    isBatchFund: boolean; // 多基金指令
    @Prop()
    isBatchStock: boolean; // 多基金指令
    Invest: any = new Invest();
    handleTextColor = handleTextColor;
    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态
    fundCodeSelectData: any[] = []; // 产品序号下拉框数据
    fundAccountCodeSelectData: any[] = []; // 组合编码下拉框数据
    allStockType: any[] = [];
    allOrderDirection: any[] = [];
    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据
    investTypeSelectData: any[] = []; // 投资类型下拉框数据
    clearSpeedSelectData: any[] = []; // 清算速度下拉数据
    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据

    tradeDays: any[] = [];

    stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    private businessTypeData: SelectOptionItemData[] = [];
    private defaultBusinessTypeData: SelectOptionItemData[] = [
        {
            label: '银行间业务',
            value: '2',
        },
    ];

    // 委托方向对应业务类型数据
    private innerOrderDirectionData: any[] = [];
    private orderDirectionData: any[] = []; // 委托方向数据

    stockInfo: any = {};

    instruction = {
        fundCode: '',
        fullPrice: '',
        fundAccountCode: '',
        stockFaceBalance: '',
        reportCode: '',
        marketCode: '',
        firstSettleDate: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        // orderDirection: '3',
        orderDirection: '',
        orderBalance: '',
        clearSpeed: '0',
        totalInterest: '', // 总应计利息
        orderPrice: '',
        settlementBalance: '', // 结算金额
        instructionTypeName: '银行间业务',
        opponentCode: '', // 交易对手编码
        businessType: '2', // 业务类型
        businClass: '2',
        // fundNameSt: '',
        // fundAccountName: '',
        stockCode: '',
    };

    // 证券代码下拉框数据相关
    stockCodeMsg = {
        url: '/original/stock/list',
        submit: {
            paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 20 },
            multStockType: ['a', '1', 'C', '5'],
            multMarketCode: ['1', '2'],
            stockCode: '',
        },
    };

    textColor: string = '';
    stockFaceBalance: string = '';
    settlementBalance: string = '';
    totalInterest: string = '';
    precision: number = 2;
    isUpDateShow: boolean = false;
    timer = null;

    @Watch('selectStockInfo', { immediate: true, deep: true })
    onWatchStockInfo() {
        if (this.selectStockInfo) {
            this.stockInfo = this.selectStockInfo;
            this.instruction.stockCode = this.selectStockInfo?.stockCode;
            this.instruction.reportCode = this.selectStockInfo?.reportCode;
            this.instruction.marketCode = this.selectStockInfo?.marketCode;
            if (this.selectStockInfo.marketCode && this.selectStockInfo.stockType) {
                this.handleStockBusinessType(this.selectStockInfo, true, true);
            }
        }
    }

    @Watch('detail', { immediate: true, deep: true })
    async onWatchDetail() {
        if (this.detail && Object.keys(this.detail).length) {
            let instruction: any = {};
            for (const key in this.detail) {
                instruction[key] = this.detail[key];
            }
            instruction.businClass = instruction.businessType;
            this.stockFaceBalance = (Number(instruction.stockFaceBalance) / 10000).toString() || '';
            this.getstockCodeList(this.instruction.stockCode);
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === instruction.stockCode);
            this.$emit('getStockInfo', this.stockInfo);
            // instruction.marketCode = this.stockInfo?.marketCode;
            this.instruction = JSON.parse(JSON.stringify(instruction));
        }
    }

    @Watch('instruction', { immediate: true, deep: true })
    setValues() {
        this.$emit('handleSettingValue', this.instruction, '2');
        this.handleFieldColor();
    }

    // 监听 组合编码计算属性 (每当计算属性变动时 自动选中第一项)
    // @Watch('computedFundAccountCodeSelectData', { immediate: true, deep: true })
    // watchcomputedFundAccountCode(newData) {
    //     if (this.detail && this.detail.instruction) {
    //         this.instruction.fundAccountCode = this.detail.instruction.fundAccountCode;
    //     } else {
    //         if (newData && newData.length) {
    //             this.instruction.fundAccountCode = newData[0].fundAccountCode;
    //         }
    //     }
    // }

    async mounted() {
        // 获取产品信息 (产品序号下拉框数据)
        this.fundCodeSelectData = await SGU_CACHE('FundInfo', '/fundInfo/list', []);
        // 获取组合编码下拉框数据
        let arr = await SGU_CACHE('FundAccount', '/fundInfo/accounts', []);
        arr.forEach(item => {
            this.fundAccountCodeSelectData[item.fundCode] = item.fundAccounts;
        });
        // 获取投资类型下拉框数据
        this.investTypeSelectData = objToArr(this.Invest.investType);
        // 获取清算速度下拉数据
        this.clearSpeedSelectData = objToArr(this.Invest.clearSpeed);
        this.getOpponentCode('');
        // 获取证券代码下拉框数据
        this.getstockCodeList(this.instruction.reportCode);

        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        // 获取所有订单方向
        this.allOrderDirection = await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []);
        this.changeSelect(false);

        // 交易日期获取 获取未来150天的交易日期
        this.getSystemTradeDay();
        this.businessTypeData = this.defaultBusinessTypeData;
        // this.instruction.businessType = this.businessTypeData[0].value;
    }

    getInputNumber(args: any) {
        let value = args[0];
        let field = args[1];
        this.instruction[field] = value;
        if (field == 'orderPrice') {
            this.handleOrderPriceChange(value);
        } else if (field == 'orderBalance') {
            this.handleOrderBalanceChange(value);
        } else if (field == 'fullPrice') {
            this.handleFullPriceChange(value);
        } else if (field == 'totalInterest') {
            this.handleTotalInterestChange();
        } else if (field == 'stockFaceBalance') {
            this.stockFaceBalance = value;
            this.handleStockFaceBalanceChange(value);
        }
    }

    handleFieldColor() {
        if (this.instruction.orderDirection === '3') {
            this.textColor = 'red';
        } else if (this.instruction.orderDirection === '4') {
            this.textColor = 'green';
        } else {
            this.textColor = '';
        }
    }

    //   获取交易对手方信息
    getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    // 更改交易对手方选择框样式
    changeSelect(state: boolean) {
        let obj = document.getElementById('multiAndSearch').parentNode.querySelector('.el-select__caret');
        obj.classList.add('el-icon-arrow-up');
        if (state) {
            obj.classList.add('is-reverse');
        } else {
            obj.classList.remove('is-reverse');
        }
    }

    getEntryslist(val: any) {
        this.instruction.fundCode = val;
        this.handleFundCodeChange(val);
    }

    handleFundCodeChange(val: string): void {
        let fund = this.fundCodeSelectData.find(item => item.fundCode === val) || {};
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || [])[0] || {};
        // this.instruction.fundNameSt = fund.fundNameSt;
        this.instruction.fundAccountCode = fundAccount.fundAccountCode;
        // this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    handleFundAccountCodeChange(value: string) {
        let fundAccount = (this.fundAccountCodeSelectData[this.instruction.fundCode] || []).find(item => item.fundAccountCode === value) || {};
        // this.instruction.fundAccountName = fundAccount.fundAccountName;
    }

    // 组合编码下拉框计算属性
    get computedFundAccountCodeSelectData() {
        return this.fundAccountCodeSelectData[this.instruction.fundCode] || [];
    }

    /**
     * 小数点后
     */
    clearNoNum(value) {
        if (!value) {
            return value;
        }
        value = String(value);
        value = value.replace(/[^\d.]/g, ''); // 清除“数字”和“.”以外的字符
        if (!value) {
            return '';
        } else {
            try {
                value = parseFloat(value).toFixed(this.precision || 0);
                return value;
            } catch (e) {
                return '';
            }
        }
    }

    // 查询未来150天的交易日期
    getSystemTradeDay() {
        this.$axios.get('/baseInfomation/system/trade/day').then((res: any) => {
            this.tradeDays = res.map(item => Number(item)).sort((a, b) => a - b);
        });
    }

    // 获取证券代码下拉框数据
    getstockCodeList(value: string) {
        this.selectLoading = true;
        try {
            clearTimeout(this.timer);
        } catch (e) {}
        this.timer = setTimeout(() => {
            this.$axios
                .post('/dict/stock/report/select/' + 3, {
                    dictKey: value,
                    dictKeyName: value,
                })
                .then((res: any) => {
                    this.stockCodeSelectData = res || [];
                    this.selectLoading = false;
                });
        }, 300);
    }

    handleVisibleChange(state: boolean) {
        if (!state) {
            this.getstockCodeList('');
        }
    }

    selectFocus(e) {
        let value = e.target.value;
        if (!value) {
            this.getstockCodeList('');
        }
    }

    // 证券代码下拉框远程搜索
    searchStockCodeList(e: string) {
        this.getstockCodeList(e);
    }

    // 根据证券代码获取对应的业务类型和委托方向
    async handleStockBusinessType(stockInfo, changeBusinessType, changeOrderDirection) {
        let res = await getBusinessType(stockInfo?.marketCode, stockInfo?.stockType);
        if (res && res.length > 0) {
            this.businessTypeData = res.map(
                item =>
                    ({
                        label: item.dictKeyName,
                        value: item.dictKey,
                    } as SelectOptionItemData)
            );
            if (this.businessTypeData.length && changeBusinessType) {
                this.instruction.businessType = this.businessTypeData[0].value;
            }
            this.innerOrderDirectionData = res;
            this.innerOrderDirectionData.filter(ele => {
                if (ele.dictKey == this.instruction.businessType) {
                    this.orderDirectionData = JSON.parse(ele['innerDictionary'] || {});
                    if (this.orderDirectionData.length && changeOrderDirection) {
                        this.instruction.orderDirection = this.orderDirectionData[0].dictKey;
                    }
                }
            });
        } else {
            this.businessTypeData = this.defaultBusinessTypeData;
        }
    }

    handleStockCodeChange(stockCode: string): void {
        if (stockCode) {
            this.stockInfo = this.stockCodeSelectData.find(item => item.stockCode === stockCode);
            this.instruction.reportCode = this.stockInfo.reportCode;
            this.instruction.marketCode = this.stockInfo.marketCode;
            this.$emit('getStockInfo', this.stockInfo);
            if (this.stockInfo.marketCode && this.stockInfo.stockType && !this.notMesh) {
                this.handleStockBusinessType(this.stockInfo, true, true);
            }
        }

        this.instruction.fullPrice = '';
        this.instruction.orderPrice = '';
        this.instruction.orderBalance = '';
        this.instruction.stockFaceBalance = '';
        this.stockFaceBalance = '';
        this.instruction.settlementBalance = '';
        this.instruction.totalInterest = '';
    }

    handleClearStockCode() {
        this.businessTypeData = this.defaultBusinessTypeData;
        this.orderDirectionData = [];
        // this.searchStockCodeList('');
        // this.instruction.businessType = this.defaultBusinessTypeData[0].value;
        if (!this.notMesh) {
            this.instruction.orderDirection = '';
            this.instruction.businessType = '';
        }
    }

    handleOrderPriceChange(val: string) {
        this.instruction.fullPrice = this.calcFullPrice(this.instruction, this.stockInfo) || '';
        this.instruction.orderBalance = this.calcOrderBalance(this.instruction, this.stockInfo) || '';
        this.instruction.settlementBalance = this.calcSettlementBalance(this.instruction, this.stockInfo);
        // this.settlementBalance = this.clearNoNum(this.instruction.settlementBalance);
        // this.totalInterest = this.clearNoNum(this.instruction.totalInterest);
    }

    handleFullPriceChange(val: string) {
        this.instruction.orderPrice = this.calcOrderPrice(this.instruction, this.stockInfo) || '';
    }

    handleStockFaceBalanceChange(val: string) {
        if (val !== '' && val !== undefined && !isNaN(Number(val))) {
            this.instruction.stockFaceBalance = (Number(val) * 10000).toString();
        }
        // let instruction = JSON.parse(JSON.stringify(this.instruction));
        this.instruction.totalInterest = this.calcTotalInterest(this.instruction, this.stockInfo);
        this.instruction.orderBalance = this.calcOrderBalance(this.instruction, this.stockInfo);
        this.instruction.settlementBalance = this.calcSettlementBalance(this.instruction, this.stockInfo);
        // this.settlementBalance = this.clearNoNum(this.instruction.settlementBalance);
        // this.totalInterest = this.clearNoNum(this.instruction.totalInterest);
    }
    handleOrderBalanceChange(val: string) {
        this.instruction.settlementBalance = this.calcSettlementBalance(this.instruction, this.stockInfo);
    }

    handleTotalInterestChange() {
        this.instruction.settlementBalance = this.calcSettlementBalance(this.instruction, this.stockInfo);
        this.settlementBalance = this.clearNoNum(this.instruction.settlementBalance);
    }

    handleClearSpeedChange(value: string) {
        if (value === '0') {
            this.instruction.firstSettleDate = moment()
                .format('YYYYMMDD')
                .toString();
        } else {
            this.instruction.firstSettleDate = this.tradeDays.find(item => item > Number(moment().format('YYYYMMDD'))).toString();
        }
    }

    /**
     * 全价价格计算公式
     */
    calcFullPrice(instruction, stockInfo) {
        let result = String((Number(instruction.orderPrice || 0) + Number(stockInfo.tDayInterest || 0)).toFixed(2));
        // let result = String(Number(instruction.orderPrice || 0) + Number(stockInfo.tDayInterest || 0));
        if (result === 'NaN' || result === 'Infinity') {
            return '0';
        } else {
            return result;
        }
    }
    /**
     * 净价价格计算公式
     */
    calcOrderPrice(instruction, stockInfo) {
        let result = String((Number(instruction.fullPrice || 0) - Number(stockInfo.tDayInterest || 0)).toFixed(2));
        // let result = String(Number(instruction.fullPrice || 0) - Number(stockInfo.tDayInterest || 0));
        if (result === 'NaN' || result === 'Infinity') {
            return '0';
        } else {
            return result;
        }
    }
    /**
     * 净价金额计算公式
     */
    calcOrderBalance(instruction, stockInfo) {
        console.log(instruction.stockFaceBalance, stockInfo.facePrice, instruction.orderPrice);

        let result = String(((Number(instruction.stockFaceBalance || 0) / Number(stockInfo.facePrice)) * Number(instruction.orderPrice)).toFixed(2));
        // let result = String((Number(instruction.stockFaceBalance || 0) / Number(stockInfo.facePrice)) * Number(instruction.orderPrice));
        if (result === 'NaN' || result === 'Infinity') {
            return '0';
        } else {
            return result;
        }
    }
    /**
     * 结算金额计算公式 净价金额+总应记利息
     */
    calcSettlementBalance(instruction, stockInfo) {
        // instruction.orderBalance = Number(instruction.orderBalance) * 10000;
        // let result = String(Number(instruction.orderBalance || 0) + Number(instruction.totalInterest || 0));
        let result = String((Number(instruction.orderBalance || 0) + Number(instruction.totalInterest || 0)).toFixed(2));
        if (result === 'NaN' || result === 'Infinity') {
            return '0';
        } else {
            return result;
        }
    }
    /**
     * 总应记利息计算公式
     */
    calcTotalInterest(instruction, stockInfo) {
        // let result = String((Number(instruction.stockFaceBalance || 0) / Number(stockInfo.facePrice)) * Number(stockInfo.tDayInterest || 0));
        let result = String(
            ((Number(instruction.stockFaceBalance || 0) / Number(stockInfo.facePrice)) * Number(stockInfo.tDayInterest || 0)).toFixed(2)
        );

        if (result === 'NaN' || result === 'Infinity') {
            return '0';
        } else {
            return result;
        }
    }
}
</script>
<style lang="scss" scoped>
@import '@/pages/risk-measure/style/measure';
.red-color {
    /deep/.el-input__inner,
    /deep/.el-input-group__append {
        color: red !important;
    }
}

.green-color {
    /deep/.el-input__inner,
    /deep/.el-input-group__append {
        color: #1c8d1c !important;
    }
}

.font-color-red {
    /deep/ input {
        color: red !important;
    }
    /deep/ .el-input-group__append {
        color: red !important;
    }
}
.font-color-green {
    /deep/ input {
        color: green !important;
    }
    /deep/ .el-input-group__append {
        color: green !important;
    }
}

.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
    }
}
</style>
